#include "drivewidget.h"

#include "qdrivebar.h"
#include "qdriveshowwidget.h"

#include "qremovedrivedialog.h"

#include "../../lib/shared/qproject.h"

#include <QVBoxLayout>

DriverWidget::DriverWidget(QWidget *parent) :
    QWidget(parent),
    m_driveBar(new QDriveBar),
    m_driveWidget(new QStackedWidget)
{
    QVBoxLayout *l=new QVBoxLayout;
    l->setMargin(0);
    l->setSpacing(0);
    l->addWidget(m_driveBar);
    l->addWidget(m_driveWidget,1);

    this->setLayout(l);
    connect(m_driveBar,SIGNAL(addWidget(int)),this,SLOT(addWidget(int)));
    connect(m_driveBar,SIGNAL(select(int)),this,SLOT(showWidget(int)));
    connect(QProject::project(),SIGNAL(openProject()),this,SLOT(projectOpen()));
    connect(QProject::project(),SIGNAL(beforeClosed()),this,SLOT(projectClose()));

    connect(m_driveBar,SIGNAL(addValue()),this,SLOT(addValue()));
    connect(m_driveBar,SIGNAL(removeSelectValue()),this,SLOT(removeSelectValue()));
    connect(m_driveBar,SIGNAL(remove()),this,SLOT(remove()));
}

void DriverWidget::addWidget(int index)
{
    QDriveShowWidget *wid=new QDriveShowWidget(QProject::project()->getDrive(index).m_name);
    m_driveWidget->addWidget(wid);
    m_widgets.append(wid);
}

void DriverWidget::showWidget(int index)
{
    if(index!=m_driveWidget->currentIndex())
    {
        m_driveWidget->setCurrentIndex(index);
    }
    m_driveBar->setSelect(index);
}

void DriverWidget::projectOpen()
{
    int k=QProject::project()->getDriveCount();
    for(int i=0;i<k;i++)
    {
        addWidget(i);
        m_driveBar->addItem(QProject::project()->getDrive(i).m_name);
    }
    if(k>0)
    {
        showWidget(0);
    }
}

void DriverWidget::projectClose()
{
    foreach(QWidget *wid,m_widgets)
    {
        m_driveWidget->removeWidget(wid);
    }
    qDeleteAll(m_widgets);
    m_widgets.clear();
    m_driveBar->clear();
}

void DriverWidget::addValue()
{
    QDriveShowWidget* wid=(QDriveShowWidget*)m_driveWidget->currentWidget();
    if(wid!=NULL)
    {
        wid->addValue();
    }
}

void DriverWidget::removeSelectValue()
{
    QDriveShowWidget* wid=(QDriveShowWidget*)m_driveWidget->currentWidget();
    if(wid!=NULL)
    {
        wid->removeSelectValue();
    }
}

void DriverWidget::remove()
{
    QRemoveDriveDialog dlg(this);

    dlg.exec();

    QList<QString>  checked=dlg.getChecked();

    QProject *p=QProject::project();
    foreach(QString str,checked)
    {
        int index=p->getDriveIndex(str);
        if(index>=0)
        {
            m_driveBar->removeItem(index);
            m_driveWidget->removeWidget(m_driveWidget->widget(index));
            p->removeDrive(index);
        }
    }
}
